var util = require('../util'),
    qrcodeService = require('./qrcode'),
    pointService = require('./point'),
    weixinuserDao   = require('../db').weixinuser,
    Promise  = require('bluebird'),
    https = require('https'),
    config = require('../util').config;

/**
 * 通过二维码关注处理
 * @param message JSON data parse from weixin xml message(FromUserName是用户, ToUserName是公众号)
 * @returns {*|exports|module.exports}
 */
function subscribeByScan (message) {
  var referncePromotionCode = message.EventKey.split('qrscene_')[1];
  return new Promise(function (resolve, reject) {
    util.weixin.getUserInfo(message.FromUserName) // 从微信平台取得用户信息
      .then(attachQrcode) // 生成用户推广用二维码
      .then(attachReference.bind(null, referncePromotionCode)) // bind第一个参数为null时, 使用Node的global对象(唯一的全局对象， 类似浏览器中的window)作为this
      .then(function (userInfo) {
        Promise.all([upsert(userInfo), // 保存用户信息
          pointService.award(userInfo, // 奖励推荐者
            referncePromotionCode,
            'subscribe_via_qrcode')])
        .then(function (results) { // 回复用户图文消息
            var upsertR = results[0];
            getSubscribeMsg(message.ToUserName, message.FromUserName).then(function (msg) {
              upsertR['action_type'] = msg.action_type + '_via_qrcode';
              upsertR['msg'] = msg.msg;
              resolve(upsertR);
            });
          });
      }).catch(util.log.log2Error);
  });
}

function subscribe (message) {
  return new Promise(function (resolve, reject) {
    util.weixin.getUserInfo(message.FromUserName)
      .then(attachQrcode)
      .then(upsert)
      .then(function (data) {
        getSubscribeMsg(message.ToUserName, message.FromUserName).then(function (msg) {
          data['action_type'] = msg.action_type;
          data['msg'] = msg.msg;
          resolve(data);
        });
      }).catch(util.log.log2Error);
  });
}

/**
 * 在注册时向用户信息中添加推广码和包含这个推广码的二维码url
 * @param userInfo
 * @returns {Promise.<T>}
 */
function attachQrcode (userInfo) {

  // 如果promotion_code为falsey" (or "falsy"), 则取得生成推广码
  userInfo.promotion_code = userInfo.promotion_code || util.generatePromotionCode(userInfo.openid);
  return Promise.resolve(qrcodeService.getQrcode(userInfo)).then(function (url) {
    userInfo.qrcode = url;
    return Promise.resolve(userInfo);
  }).catch(util.log.log2Error);
}

function attachReference (reference, userInfo) {
  userInfo.reference_code = reference;
  return userInfo;
}
/**
 * 以data为检索条件, 有则update, 无则insert
 * @param data 检索条件
 * @returns {Promise}
 */
function upsert(user) {
  return weixinuserDao.findByOpenId(user.openid).then(function(data) {

    // 微信的时间戳精确到秒, 需转换为毫秒
    if (user.subscribe_time) user.subscribe_time = user.subscribe_time * 1000;

    // 已经有数据，只更新subscribe-time和推荐者code
    if (data) {
      user = {
        openid        : data.openid,
        subscribe_time: Date.now(),
        reference_code: user.reference_code || '' //使用最新的推荐者code, 没有则置为''
      }
    }
    return weixinuserDao.upsert({openid: user.openid}, user);
  }).catch(util.log.log2Error);
}

function getSubscribeMsg (msgFrom, msgTo) {
  return weixinuserDao.findByOpenId(msgTo).then(function (userInfo) {
    var description = '↑↑↑ 点击图片获取您的推广码 ↑↑↑\r\n\
  ' + userInfo.nickname +', 您好！\r\n\
  感谢关注科研共济会\r\n\
  请回复你的edu邮箱完成注册\r\n\
  分享二维码可以获得更多vpn免费时间\r\n';

    var item = util.weixin.getNewsItem('欢迎来的科研共济会', description, userInfo.qrcode, userInfo.qrcode);
    var msg = util.weixin.getNewsMsg(msgFrom, msgTo, new Array(item));
    return Promise.resolve({
      action_type: 'subscribe',
      msg: msg
    });
  }).catch(util.log.log2Error);
}

module.exports = {
  getSubscribeMsg: getSubscribeMsg,
  subscribeByScan: subscribeByScan,
  subscribe: subscribe
};